class BlogsController < ApplicationController
  before_action :set_blogs_for_current_user, only: [ :edit, :update, :destroy]
  # 在需要修改的时候，就需要进行用户验证了！所以里面并没有show, 因为不需要用户验证，你的博客就是让人看的！
  before_action :authenticate_devise_user! , only:[:new, :edit, :create, :update, :destroy]
  # layout false 通过这种方法来关闭自动的layout到application.html.erb

  def update_categories # 修改categories
    category_ids=params[:category_ids]
    @blogs.category_ids=category_ids
  end

  def flashout
    @output=flash.map { |type,message|
      "type and message is #{type}:#{message}"
    }
  end
  # GET /blogs
  # GET /blogs.json
  def index
    # 有了application_helper中notice_message，显示的信息都变成了bootstrap风格。
    # flash[:notice]="good morning"
    # @blogs = Blog.all
    @blogs = Blog
    @blogs = @blogs.order(params[:sort]) if params[:sort]
    @blogs = @blogs.all
  end

  # GET /blogs/1
  # GET /blogs/1.json
  def show
    @blog = Blog.find(params[:id])  # 因为有了set_blogs_for_current_user, 所以，在显示的时候就不用再验证用户了
  end

  # GET /blogs/new
  def new
    @blog = Blog.new
  end

  # GET /blogs/1/edit
  def edit
  end

  # POST /blogs
  # POST /blogs.json
  def create
    @blog = current_devise_user.blogs.new(blog_params)

    respond_to do |format|
      if @blog.save
        # format.html { redirect_to @blog, notice: '博客新建成功。' }
        format.html {
          flash[:notice]='博客新建成功。'
          redirect_to @blog
        }
        format.json { render :show, status: :created, location: @blog }
      else
        format.html { render :new }
        format.json { render json: @blog.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /blogs/1
  # PATCH/PUT /blogs/1.json
  def update
    respond_to do |format|
      if @blog.update(blog_params)
        # format.html { redirect_to @blog, notice: '博客成功修改。' }
        format.html {
          flash[:notice]='博客成功修改。'
          redirect_to @blog
        }
        format.json { render :show, status: :ok, location: @blog }
      else
        format.html { render :edit }
        format.json { render json: @blog.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /blogs/1
  # DELETE /blogs/1.json
  def destroy
    @blog.destroy
    respond_to do |format|
      format.html { redirect_to blogs_url, notice: '博客成功删除。' }
      format.json { head :no_content }
    end
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_blogs_for_current_user
    # @blog = Blog.find(params[:id])
    @blog = current_devise_user.blogs.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def blog_params
    params.require(:blog).permit(:title, :content, :time, :visible)
  end
end
